﻿
Imports System.ComponentModel
'http://coolthingoftheday.blogspot.com/2005/11/fun-with-bindinglistof-t-and-bindable.html
Public Class GJSortableBindingList(Of T)
    Inherits System.ComponentModel.BindingList(Of T)

    Private m_Sorted As Boolean = False
    Private m_SortDirection As ListSortDirection
    Private m_SortProperty As PropertyDescriptor

    'Protected Overrides Function AddNewCore() As Object
    '    Dim c As New T
    '    Add(c)
    '    Return c
    'End Function

#Region "Sorting Support"
    Protected Overrides Sub ApplySortCore(ByVal prop As System.ComponentModel.PropertyDescriptor, _
      ByVal direction As System.ComponentModel.ListSortDirection)

        ' Get list to sort
        Dim items As List(Of T) = TryCast(Me.Items, List(Of T))

        ' Apply and set the sort, if items to sort
        If items IsNot Nothing Then

            m_SortDirection = direction
            m_SortProperty = prop

            Dim pc As PropertyComparer(Of T) = _
              New PropertyComparer(Of T)(prop, direction)

            items.Sort(pc)
            m_Sorted = True

        Else
            m_Sorted = False

        End If

        Me.OnListChanged(New ListChangedEventArgs(ListChangedType.Reset, -1))
    End Sub

    Protected Overrides ReadOnly Property SupportsSortingCore() As Boolean
        Get
            Return True
        End Get
    End Property

    Protected Overrides ReadOnly Property IsSortedCore() As Boolean
        Get
            Return m_Sorted
        End Get
    End Property

    Protected Overrides Sub RemoveSortCore()
        m_Sorted = False
    End Sub

    Protected Overrides ReadOnly Property SortDirectionCore() As System.ComponentModel.ListSortDirection
        Get
            Return m_SortDirection
        End Get
    End Property

    Protected Overrides ReadOnly Property SortPropertyCore() As System.ComponentModel.PropertyDescriptor
        Get
            Return m_SortProperty
        End Get
    End Property

#End Region



End Class
